#!/bin/sh
#
# choose -- Choose a lab
#
# Copyright (C) 2016-2020 Wu Zhangjin <lzufalcon@163.com>
#

NEW_LAB=$1

uname | grep -q MINGW && PWD_OPT="-W"
TOP_DIR="$(cd "$(dirname "$0")"/../../ && pwd $PWD_OPT)"
. "$TOP_DIR/tools/docker/config" $* >/dev/null
OLD_LAB=$CURRENT

[ -z "$PULL" ] && PULL=0

[ -z "$SUBMODULE" ] && SUBMODULE=0

# Fix up windows support
config_casesensitive ()
{
   # should enable case sensitive for ntfs filesystem
   uname | grep -q MINGW && fsutil file SetCaseSensitiveInfo $TOP_DIR enable >/dev/null 2>&1
}

config_git ()
{
    git config --global core.safecrlf true
    git config --global core.autocrlf false
}

download_submodule ()
{
    LAB_CURRENT_DIR="$LAB_DIR/$CURRENT"
    LAB_LABS="$CONFIG_DIR/labs"

    if [ -n "$CURRENT" ]; then
      LABS=$CURRENT
    else
      get_var LABS $CURRENT
    fi

    for lab in $LABS; do
      LAB_CURRENT_DIR="$LAB_DIR/$lab"
      [ $SUBMODULE -eq 1 ] && \
	RECURSIVE=" --recursive " && \
	PULL_RECURSIVE=" --recurse-submodules=yes "

      [ ! -f "$LAB_CURRENT_DIR/.git" ] \
        && git submodule update --init --remote $RECURSIVE "$LAB_CURRENT_DIR" \
        && cd "$LAB_CURRENT_DIR" && git checkout $BRANCH

      [ $PULL -eq 1 ] && echo "LOG: Pulling repository: $lab" \
        && git pull -v && git submodule sync && git pull $PULL_RECURSIVE -v

      [ $SUBMODULE -eq 1 ] && echo "LOG: Pulling submodules of $lab" \
	&& git submodule update --init --remote $RECURSIVE .

      # Convert absolute path to relative path for gitdir in .git of submodules
      [ $SUBMODULE -eq 1 ] && \
        git submodule foreach --recursive '[ -f .git ] && gitdir=$(cut -d" " -f2 .git) && (echo $gitdir | grep -q ^/) && dir=$(echo $gitdir | sed -e 's%$TOP_DIR/%%') && relpath=$(echo $PWD | sed -e 's%$TOP_DIR%%g' | tr -c -d '/' | sed -e 's%/%../%g') && echo "gitdir: $(echo $relpath)$dir" > .git || :'

      echo "LOG: Source code downloaded to $LAB_CURRENT_DIR"
    done
}

if [ -n "$NEW_LAB" ]; then
    . "$TOP_DIR/tools/docker/config" $NEW_LAB >/dev/null

    set_var CURRENT

    [ -n "$OLD_LAB" -a "$OLD_LAB" != "$CURRENT" ] && echo "LOG: Switch from $OLD_LAB to $CURRENT"
    download_submodule && exit 0
fi

echo "LOG: Available Labs:\n"
echo $LABS | tr ' ' '\n' | cat -n
echo ""

read -p 'LOG: Choose the lab number: ' number

[ -z "$number" ] && echo "\nERR: No valid number specified.\n" && exit 1

CURRENT=`echo $LABS | tr ' ' '\n' | head -$number | tail -1`

echo "\n     $number\t$CURRENT\n"

set_var CURRENT

echo "\nLOG: Download the lab...\n"

# Hacking for windows support, disable autocrlf switch
config_git
config_casesensitive

# Clone the submodule
download_submodule
